//
//  EAGLView.m
//  TextureWrap
//
//  Created by Dan Ginsburg on 6/13/09.
//  Copyright __MyCompanyName__ 2009. All rights reserved.
//



#import "EAGLView.h"

#include "../AirSDK/AirGraphics/AirGraphics.h"
#include "../AirSDK/AirGraphics/AirGraphicsContext/AirGraphicsContext.h"
#include "../AirSDK/AirGraphics/AirGraphicsScene.h"
#include "AirFireWorksRender.h"
#include "../AirSDK/AirGraphics/AirParticleSysRender.h"

//#include "AGRenderParticleSystem.h"
// A class extension to declare private methods

char*  OSLoadPNG ( char *fileName, int *width, int *height )
{
	NSString *filePath = [NSString stringWithUTF8String: fileName];
	NSString *path = [[NSBundle mainBundle] pathForResource: filePath ofType:@"png"];
    NSData *texData = [[NSData alloc] initWithContentsOfFile:path];
    UIImage *image = [[UIImage alloc] initWithData:texData];
    
    *width = CGImageGetWidth(image.CGImage);
    *height = CGImageGetHeight(image.CGImage);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    void *imageData = malloc( *height * *width * 4 );
    CGContextRef context = CGBitmapContextCreate( imageData, *width, *height, 8, 4 * *width, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big );
    CGColorSpaceRelease( colorSpace );
    CGContextClearRect( context, CGRectMake( 0, 0, *width, *height ) );
    CGContextTranslateCTM( context, 0, *height - *height );
    CGContextDrawImage( context, CGRectMake( 0, 0, *width, *height ), image.CGImage );
	
    CGContextRelease(context);
	return (char *)imageData;
};

@interface EAGLView ()
@property(nonatomic) AirCpp::AirGraphics *graphics;
@property(nonatomic) AirCpp::AirGraphicsContext *p_AGcontext;
@property(nonatomic) AirCpp::AirGraphicsScene *rootSence;
@end

@implementation EAGLView
@synthesize context, animationTimer, animationInterval;

// You must implement this method
+ (Class)layerClass {
    return [CAEAGLLayer class];
}

- (id)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startDrawing) name:@"StartDrawing" object:nil];
        self.p_AGcontext = new AirCpp::AirGraphicsContext();
        if (self.p_AGcontext->init((__bridge void *)self.layer) != -1) {
            DebugLog("AGcontext init Succuess!! \n");
        }
        
        self.graphics = new AirCpp::AirGraphics();
        if (self.graphics->init(frame.size.width, frame.size.height,AirCpp::USE_DEPTH_BUFFER, self.p_AGcontext) != -1) {
            DebugLog("AirGraphics init Succuess!! \n");
        }
        
        self.rootSence = new AirCpp::AirGraphicsScene();
        
        // Get the layer
        char *fsh = NULL;
        char *vsh = NULL;
        fsh = (char *)[[[NSBundle mainBundle] pathForResource:@"AirFireWorksShader" ofType:@"fsh"] UTF8String];
        vsh = (char *)[[[NSBundle mainBundle] pathForResource:@"AirFireWorksShader" ofType:@"vsh"] UTF8String];
        FireWorksRender *fireWorks = new FireWorksRender();
        fireWorks->init(new AirCpp::AirCoordinate3D(0, 0, 0), new AirCpp::AirPosition3D(0, 0, 0), vsh, fsh, 30);
        fireWorks->compire_shader_program();
        self.rootSence->init(self.graphics, fireWorks);
    }
    return self;
}

- (void)startDrawing{
    NSTimeInterval curTick = [NSDate timeIntervalSinceReferenceDate];
    prevTick = curTick;
    self.rootSence->rend(true);
    [self performSelector:@selector(startDrawing) withObject:nil afterDelay:1.0f/60.0f];
    return;
    //在百万次调用测试中，内联和虚函数性能损失不超过0.01秒（虚拟机）性能可以接受
}

- (void)layoutSubviews {
    [EAGLContext setCurrentContext:context];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    release(self.rootSence);
    release(self.p_AGcontext);
    release(self.graphics);
}

@end
